package com.syni.mdd.sjb.common.datatreaure.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.syni.mdd.sjb.common.component.mybatis.dxshapp.entity.DxshAppServiceOrder;
import com.syni.mdd.sjb.common.component.mybatis.dxshapp.entity.DxshAppServices;
import com.syni.mdd.sjb.common.component.mybatis.dxshapp.entity.DxshAppSmsService;
import com.syni.mdd.sjb.common.component.mybatis.dxshapp.entity.DxshAppUserSms;
import com.syni.mdd.sjb.common.component.mybatis.dxshapp.mapper.DxshAppServiceOrderMapper;
import com.syni.mdd.sjb.common.component.utils.common.utils.ResultMapHelper;
import com.syni.mdd.sjb.common.component.utils.common.utils.RpcResponseVo;
import com.syni.mdd.sjb.common.component.utils.feign.dto.mddAll.apiPay.AliPayPrepayDto;
import com.syni.mdd.sjb.common.component.utils.feign.service.mddAll.PayRestService;
import com.syni.mdd.sjb.common.datatreaure.service.*;
import com.syni.mdd.sjb.common.datatreaure.config.pay.alipay.PayConfig;
import com.syni.mdd.sjb.common.datatreaure.constants.Constants;
import com.syni.mdd.sjb.common.datatreaure.constants.ResultCode;
import com.syni.mdd.sjb.common.datatreaure.constants.ResultMsg;
import com.syni.mdd.sjb.common.datatreaure.entity.vo.rq.pay.PayRqVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Service
public class AlipayServiceImpl implements AlipayService {
    @Autowired
    @Qualifier("payConfig")
    PayConfig payConfig;

    @Autowired
    DxshAppServiceOrderService dxshAppServiceOrderService;

    @Autowired
    DxshAppServiceOrderMapper dxshAppServiceOrderMapper;

    @Autowired
    DxshAppSmsServiceService dxshAppSmsServiceService;

    @Autowired
    DxshAppUserSmsService dxshAppUserSmsService;

    @Autowired
    DxshAppServicesService dxshAppServicesService;

    @Autowired
    PayRestService payRestService;


    private Logger log = LoggerFactory.getLogger(AlipayServiceImpl.class);

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void appAliPayNotify(HttpServletRequest request) {
        System.out.println("----------------阿里服务器消费手机回调-------" + request);
        Map<String, String> params = new HashMap<>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }
        log.info("回调数据：" + JSON.toJSONString(params));
        try {
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
            // 交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            if ( trade_status.equals("TRADE_SUCCESS")) {
                //TODO
                // 修改订单状态
                // 已缴费----开始处理业务
                log.info(out_trade_no +" 用户已付款：.................................." +trade_no);
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq(DxshAppServiceOrder.ORDER_NO,out_trade_no);
                DxshAppServiceOrder dxshAppServiceOrder = dxshAppServiceOrderService.getOne(queryWrapper);
                if(dxshAppServiceOrder.getStatus() == DxshAppServiceOrderService.NO_PAY_STATUS){
                    //处理订单业务逻辑
                    switch(dxshAppServiceOrder.getOrderType()){
                        case DxshAppServiceOrderService.addedType :
                            //增值服务类型
                            queryWrapper.clear();
                            queryWrapper.eq(DxshAppServices.ID,dxshAppServiceOrder.getServiceId());
                            DxshAppServices dxshAppServices = dxshAppServicesService.getOne(queryWrapper);
                            if(dxshAppServices != null){
                                dxshAppServices.setBuyNum(dxshAppServices.getBuyNum()+1);
                                dxshAppServicesService.saveOrUpdate(dxshAppServices);
                            }
                            break;
                        case DxshAppServiceOrderService.smsType:
                            //短信类型
                            queryWrapper.clear();
                            queryWrapper.eq(DxshAppSmsService.ID,dxshAppServiceOrder.getServiceId());
                            DxshAppSmsService dxshAppSmsService = dxshAppSmsServiceService.getOne(queryWrapper);
                            queryWrapper.clear();
                            queryWrapper.eq(DxshAppUserSms.USER_ID,dxshAppServiceOrder.getBmsUserId());

                            DxshAppUserSms dxshAppUserSms = dxshAppUserSmsService.getOne(queryWrapper);
                            if(dxshAppSmsService != null && dxshAppUserSms != null){
                                dxshAppUserSms.setSmsNum(dxshAppUserSms.getSmsNum() + dxshAppSmsService.getNumber());
                                dxshAppUserSmsService.saveOrUpdate(dxshAppUserSms);
                                log.info(String.format("短信充值执行成功  userid:%s,充值数量:%s",dxshAppServiceOrder.getId(),dxshAppSmsService.getNumber()));
                            }
                            break;
                        default:break;

                    }

                    //修改订单状态
                    dxshAppServiceOrder.setPayNo(trade_no);
                    dxshAppServiceOrder.setStatus(DxshAppServiceOrderService.PAY_STATUS);
                    dxshAppServiceOrder.setPayStatus(DxshAppServiceOrderService.PAY_STATUS);
                    dxshAppServiceOrder.setTalkStatus(Constants.COMMON_FLAG_FALSE_INT);
                    dxshAppServiceOrder.setServeTime(LocalDateTime.now());
                    dxshAppServiceOrder.setPayTime(LocalDateTime.now());
                    dxshAppServiceOrder.setPayWay(1);
                    dxshAppServiceOrderMapper.updateById(dxshAppServiceOrder);
                    log.info(" ------------------>  充值/购买 回调完毕  <---------------------");
                    log.info(dxshAppServiceOrder.toString());

                    //推送服务

                }


            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            log.error(e.getMessage(),e);
            //orderLog.setPayError(e.toString());
        }
    }



    @Override
    public Map<String, Object> prepay(PayRqVo payRqVo) {

        if(payRqVo.getIsCustomize() == Constants.COMMON_FLAG_TRUE_INT){
            AliPayPrepayDto aliPayPrepayDto = new AliPayPrepayDto();
            aliPayPrepayDto.setOrderNo(payRqVo.getOrderNo());
            aliPayPrepayDto.setTotalAmt(payRqVo.getTotalAmt());
            aliPayPrepayDto.setNotifyUrl(payRqVo.getNotifyUrl());
            RpcResponseVo rpcResponseVo = payRestService.aliPayPrepay(aliPayPrepayDto);
            if(rpcResponseVo.isSuccess()){
                aliPayPrepayDto = JSON.parseObject(JSON.toJSONString(rpcResponseVo.getData()),AliPayPrepayDto.class);
                return ResultMapHelper.success(aliPayPrepayDto.getPayCredent(), ResultMsg.MSG_GET_SUCCESS);
            }
            return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
        }else{
            //检验订单号和订单id是否一致
            DxshAppServiceOrder dxshAppServiceOrder = dxshAppServiceOrderService.getOne(new QueryWrapper<DxshAppServiceOrder>().eq(DxshAppServiceOrder.ID,payRqVo.getOrderId()));
            if (dxshAppServiceOrder == null) {
                return ResultMapHelper.result(ResultCode.CODE_ORDER_NO_EXIST, ResultMsg.CODE_ORDER_NO_EXIST);
            }
            if (!dxshAppServiceOrder.getOrderNo().equals(payRqVo.getOrderNo())) {
                return ResultMapHelper.result(ResultCode.CODE_ORDER_ID_NOMATCH_NO, ResultMsg.CODE_ORDER_ID_NOMATCH_NO);
            }
            if(!(dxshAppServiceOrder.getStatus() == Constants.COMMON_FLAG_FALSE_INT)){
                return ResultMapHelper.failure("非待支付状态");
            }

            AliPayPrepayDto aliPayPrepayDto = new AliPayPrepayDto();
            aliPayPrepayDto.setOrderNo(payRqVo.getOrderNo());
            aliPayPrepayDto.setTotalAmt(dxshAppServiceOrder.getTotalPrice().toString());
            aliPayPrepayDto.setNotifyUrl(payConfig.getAlicallBackUrl());
            RpcResponseVo rpcResponseVo = payRestService.aliPayPrepay(aliPayPrepayDto);
            if(rpcResponseVo.isSuccess()){
                aliPayPrepayDto = JSON.parseObject(JSON.toJSONString(rpcResponseVo.getData()),AliPayPrepayDto.class);
                return ResultMapHelper.success(aliPayPrepayDto.getPayCredent(),ResultMsg.MSG_GET_SUCCESS);
            }
            return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
        }

    }
}
